package com.health.work.activity;


import java.util.ArrayList;
import java.util.HashMap;
import com.health.work.R;
import com.health.work.utils.HEALTHPASSPORT;
import com.health.work.utils.TipsUtil;
import com.health.work.utils.UserInfoUtils;
import com.health.work.utils.WebUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class HealthArchivesActivity extends Activity implements
		OnClickListener, OnGestureListener {
	
	private static LayoutInflater mInflater;
	private String[] information;
	private String[] information_have;
	private static ListView informationListview;
	private Context mContext;
	private String username;
	private String password;
	private TextView idcardTextView;
	private TextView nameTextView;
	private TextView sexTextView;
	private TextView oldTextView;
	private TextView addressTextView;
	private TextView checkDateTextView;
	private TextView hospNameTextView;
	private Button back;
	private HashMap<String, Object> informationHashMap;
	private HashMap<String, Object> informationString;
	private HashMap<String, String> itemHashMap_detail;
	private HashMap<String, Object> infomationDateList;
	private HashMap<String, Object> infomationDateRecord;
	private AlertDialog ad;
	private static String FileName;
	private ProgressDialog downDialog;
	private static int DATE_NOW = 0;
	private GestureDetector detector;
	private ViewFlipper flipper;
	private ProgressDialog loadDialog;
	private String[] update_result;
	public static String[] HealthItem;
	private String[] healthitem_result;
	private ArrayList<String> l=new ArrayList<String>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.health_archives_layout);
		mContext = getApplication();
		flipper = (ViewFlipper) this.findViewById(R.id.ViewFlipper01);
		detector = new GestureDetector(this);
		information_have = new String[20];

		// 初始化各控件
		nameTextView = (TextView) findViewById(R.id.information_name);
		sexTextView = (TextView) findViewById(R.id.information_sex);
		oldTextView = (TextView) findViewById(R.id.information_old);
		addressTextView = (TextView) findViewById(R.id.information_address);
		idcardTextView = (TextView) findViewById(R.id.information_identity);
		checkDateTextView = (TextView) findViewById(R.id.information_checkDate);
		hospNameTextView = (TextView) findViewById(R.id.information_hospName);
		back = (Button) findViewById(R.id.btnBack);

		// 获得后退键监听
		back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});

		if(UserInfoUtils.getUserProperty(this, HEALTHPASSPORT.IDNUMBER)!=null
				&&!UserInfoUtils.getUserProperty(this, HEALTHPASSPORT.IDNUMBER).trim().equals("null")){
			username=UserInfoUtils.getUserProperty(this, HEALTHPASSPORT.IDNUMBER);
		
//			username = "341224200211179870";//省份证号
			password = "123";
			
			// zhai add
			informationHashMap = WebUtils.GetEHR(username, password);
			// zhai ended
			
			healthitem_result = WebUtils.GetItems(username,password).split("@");
			if(healthitem_result[0].equals("true")){
				information = WebUtils.getEHRItems();
	         }
			
			if(information==null || information.length==0){
				Toast.makeText(this, "您所在地尚未加入健康护照协议地区", Toast.LENGTH_SHORT).show();
			}
			
			if(informationHashMap!=null && informationHashMap.size()>0){
				initData();
			}else{
				Toast.makeText(this, "您所在地尚未加入健康护照协议地区", Toast.LENGTH_SHORT).show();
			}
		
		}else{
			TipsUtil.showAlertFinish(this, null, "您不是查档会员，不能查询本人健康档案");
		}
		
	}

	private void initData(){

				infomationDateList = (HashMap<String, Object>) informationHashMap
						.get("EHRecords");

		        infomationDateRecord = (HashMap<String, Object>)infomationDateList.get(WebUtils.getLIST_CHECKDATE().get(DATE_NOW));
				informationString = (HashMap<String, Object>) infomationDateRecord
						.get("EHRlist");
				for (int i = 0, j = 0; i < informationString.size(); i++) {
					if ((HashMap<String, String>) informationString.get(information[i]) != null) {
						information_have[j] = information[i];
						j++;
					}
				}
				Log.d("guojie", "informationString  " + informationString.toString());

				// 获得数据
				nameTextView.setText((String) informationHashMap.get("Name"));
				if (((String) (informationHashMap.get("Sex"))).equals("2")) {
					sexTextView.setText(getString(R.string.female));
				} else {
					sexTextView.setText(getString(R.string.male));
				}
				oldTextView.setText((String) informationHashMap.get("Age"));
				addressTextView.setText((String) informationHashMap.get("Address"));
				idcardTextView.setText((String) informationHashMap.get("IdCardNo"));
				checkDateTextView.setText((String) infomationDateRecord
						.get("CheckDate"));
				hospNameTextView.setText((String) infomationDateRecord.get("HospName"));

				// //获得listview数据
				information = getResources().getStringArray(
						R.array.information_listarray);
				informationListview = (ListView) findViewById(R.id.information_detail_list);
				HealthInformationListAdapter informationListAdapter = new HealthInformationListAdapter(
						mContext);
				informationListview.setAdapter(informationListAdapter);
				informationListview.setCacheColorHint(0);

				// //获得listview点击
				informationListview
						.setOnItemClickListener(new AdapterView.OnItemClickListener() {
							public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
								itemHashMap_detail = (HashMap<String, String>) informationString
										.get(information_have[position]);
								if (itemHashMap_detail == null) {
									ad = new AlertDialog.Builder(
											HealthArchivesActivity.this)
											.setTitle(getString(R.string.ad_tittle))
											.setMessage(getString(R.string.ad_null))
											.setPositiveButton(
													getString(R.string.ad_makesure),
													new DialogInterface.OnClickListener() {
														@Override
														public void onClick(
																DialogInterface dialog,
																int which) {
															ad.dismiss();
														}
													}).show();
								} else {
									ad = new AlertDialog.Builder(
											HealthArchivesActivity.this)
											.setTitle(getString(R.string.ad_tittle))
											.setMessage(
													itemHashMap_detail
															.get("ClinicalMeaning"))
											.setPositiveButton(
													getString(R.string.ad_makesure),
													new DialogInterface.OnClickListener() {
														@Override
														public void onClick(
																DialogInterface dialog,
																int which) {
															ad.dismiss();
														}
													}).show();
								}
							}
						});
	}
	
	/** holder定义 **/
	public class ViewHolder {
		public TextView itemText;
		public TextView thisText;
		public TextView normalText;
		public TextView conclusionText;
	}

	/** listview适配器 **/
	public class HealthInformationListAdapter extends BaseAdapter {
		public HealthInformationListAdapter(Context context) {
			mInflater = LayoutInflater.from(HealthArchivesActivity.this);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return informationString.size();
			// return informationString.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater
						.inflate(R.layout.information_list, null);
				holder.itemText = (TextView) convertView
						.findViewById(R.id.list_item);
				holder.thisText = (TextView) convertView
						.findViewById(R.id.list_this);
				holder.normalText = (TextView) convertView
						.findViewById(R.id.list_normal);
				holder.conclusionText = (TextView) convertView
						.findViewById(R.id.list_conclusion);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			HashMap<String, String> itemHashMap = (HashMap<String, String>) informationString
					.get(information_have[position]);
			if (itemHashMap == null) {
				/*
				 * holder.itemText.setText(information[position]);
				 * holder.thisText.setText(getString(R.string.item_null));
				 * holder.normalText.setText(getString(R.string.item_null));
				 * holder.conclusionText.setText(getString(R.string.item_null));
				 * holder
				 * .conclusionText.setTextColor(getResources().getColor(android
				 * .R.color.black));
				 */
			} else {
				String result = itemHashMap.get("ItemValueDesc");
				String min = itemHashMap.get("NormalValue1");
				String max = itemHashMap.get("NormalValue2");
				Log.d("renmeng",
						itemHashMap.get("ItemValueDesc")
								+ itemHashMap.get("ItemUnit"));
				holder.itemText.setText(information[position]);
				holder.thisText.setText(result + itemHashMap.get("ItemUnit"));
				holder.normalText.setText(min + "-" + max
						+ itemHashMap.get("ItemUnit"));
				if (itemHashMap.get("Tips").equals("")) {
					holder.conclusionText
							.setText(getString(R.string.conclusion_normal));
				} else if (itemHashMap.get("Tips").equals("1")) {
					holder.conclusionText
							.setText(getString(R.string.conclusion_normal));
				} else if (itemHashMap.get("Tips").equals("2")) {
					holder.conclusionText
							.setText(getString(R.string.conclusion_high));
				} else if (itemHashMap.get("Tips").equals("3")) {
					holder.conclusionText
							.setText(getString(R.string.conclusion_low));
				} else if (itemHashMap.get("Tips").equals("4")) {
					holder.conclusionText
							.setText(getString(R.string.conclusion_excep));
				}

			}
			return convertView;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		Log.d("guojie", "Fling Happened!");
		if (e1.getX() - e2.getX() > 20) {
			Log.d("guojie", "向左滑动");
			if ((DATE_NOW + 1) < WebUtils.getLIST_CHECKDATE()
					.size()) {
				DATE_NOW++;
				Log.d("guojie", "DATE_NOW ++===" + DATE_NOW);
				// 更新页面
				this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
						R.anim.push_left_in));
				this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
						R.anim.push_left_out));
				this.flipper.showNext();
				setNewView();
			}
			return true;
		} else if (e1.getX() - e2.getX() < -20) {
			Log.d("guojie", "向右滑动");
			if ((DATE_NOW - 1) >= 0) {
				DATE_NOW--;
				Log.d("guojie", "DATE_NOW --===" + DATE_NOW);
				// 更新页面
				this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
						R.anim.push_right_in));
				this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
						R.anim.push_right_out));
				this.flipper.showPrevious();
				setNewView();
			}
			return true;
		}
		return true;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		return this.detector.onTouchEvent(event);
	}

	private void setNewView() {
		Log.d("guojie", "WebUtils.getLIST_CHECKDATE().get(DATE_NOW)  "
				+ WebUtils.getLIST_CHECKDATE().get(DATE_NOW)
						.toString());
		infomationDateRecord = (HashMap<String, Object>) infomationDateList
				.get(WebUtils.getLIST_CHECKDATE().get(DATE_NOW));
		informationString = (HashMap<String, Object>) infomationDateRecord
				.get("EHRlist");
		Log.d("guojie", "informationString  " + informationString.toString());
		// 初始化各控件
		nameTextView = (TextView) findViewById(R.id.information_name);
		sexTextView = (TextView) findViewById(R.id.information_sex);
		oldTextView = (TextView) findViewById(R.id.information_old);
		addressTextView = (TextView) findViewById(R.id.information_address);
		idcardTextView = (TextView) findViewById(R.id.information_identity);
		checkDateTextView = (TextView) findViewById(R.id.information_checkDate);
		hospNameTextView = (TextView) findViewById(R.id.information_hospName);
		back = (Button) findViewById(R.id.btnBack);
		Log.d("renmeng", (String) informationHashMap.get("Name"));

		// 获得后退键监听
		back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.putExtra("qrCode", "");
				intent.setClass(HealthArchivesActivity.this, MainActivity.class);
				startActivity(intent);
			}
		});

		// 获得数据
		nameTextView.setText((String) informationHashMap.get("Name"));
		if (((String) (informationHashMap.get("Sex"))).equals("2")) {
			sexTextView.setText(getString(R.string.female));
		} else {
			sexTextView.setText(getString(R.string.male));
		}
		oldTextView.setText((String) informationHashMap.get("Age"));
		addressTextView.setText((String) informationHashMap.get("Address"));
		idcardTextView.setText((String) informationHashMap.get("IdCardNo"));
		checkDateTextView.setText(WebUtils.getLIST_CHECKDATE()
				.get(DATE_NOW).toString());
		hospNameTextView.setText((String) infomationDateRecord.get("HospName"));
		informationListview = (ListView) findViewById(R.id.information_detail_list);
		HealthInformationListAdapter informationListAdapter = new HealthInformationListAdapter(
				mContext);
		informationListview.setAdapter(informationListAdapter);
		informationListview.setCacheColorHint(0);

		// 获得listview点击
		informationListview
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						itemHashMap_detail = (HashMap<String, String>) informationString
								.get(information_have[position]);
						if (itemHashMap_detail == null) {
							ad = new AlertDialog.Builder(
									HealthArchivesActivity.this)
									.setTitle(getString(R.string.ad_tittle))
									.setMessage(getString(R.string.ad_null))
									.setPositiveButton(
											getString(R.string.ad_makesure),
											new DialogInterface.OnClickListener() {
												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													ad.dismiss();
												}
											}).show();
						} else {
							ad = new AlertDialog.Builder(
									HealthArchivesActivity.this)
									.setTitle(getString(R.string.ad_tittle))
									.setMessage(
											itemHashMap_detail
													.get("ClinicalMeaning"))
									.setPositiveButton(
											getString(R.string.ad_makesure),
											new DialogInterface.OnClickListener() {
												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													ad.dismiss();
												}
											}).show();
						}
					}
				});
	}

}